package com.jhgsys.internal.hazard.controller.upload;

import com.jhgsys.internal.common.constant.FileUploadConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.utils.Plupload;
import com.jhgsys.internal.common.utils.PluploadUtil;
import com.jhgsys.internal.common.utils.UploadPathUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @Author wanghw
 * @CreateTime 2024/8/8 16:47
 * @Description TODO
 * @Version 1.0
 */
@Controller()
public class HazardUploadController {
    public static String MSG_ERROR_FILE_TYPE = "文件类型不正确！";
    public static String MSG_ERROR_NO_FILE = "未包含上传文件！";
    // 文件允许格式
    private String[] allowImageFiles = { ".gif", ".png", ".jpg", ".jpeg", ".bmp" };
    private String[] allowVideoFiles = { ".swf", ".wmv", ".mpg", ".m4v", ".mp4", ".flv", ".3gp", ".avi", ".rmvb", ".mkv"};
    private String[] allowOtherFiles = { ".rar", ".zip", ".pdf", ".txt", ".ppt", ".pptx", ".doc", ".docx", ".xls", ".xlsx" };


    @RequestMapping(value = "hazard/upload", method = RequestMethod.POST)
    @ResponseBody
    public FebsResponse uploadImage(Plupload plupload, HttpServletRequest request) {
        if (!checkFileType(plupload.getName(), allowImageFiles)
                &&!checkFileType(plupload.getName(), allowVideoFiles)
                &&!checkFileType(plupload.getName(), allowOtherFiles)) {
            return new FebsResponse().fail().message(MSG_ERROR_FILE_TYPE);
        }
        plupload.setFilePath(FileUploadConstant.HAZARD_FILE_PATH);
        FebsResponse objects = fileUpCommon(plupload, request, plupload.getFilePath());
        return objects;
    }


    public static FebsResponse fileUpCommon(Plupload plupload, HttpServletRequest request, String path) {
        plupload.setRequest(request);
        try {
            String videoPath = path + "/" + dateFormat();
            File dir = new File(UploadPathUtil.getRootPath() + videoPath);
            //上传文件
            PluploadUtil.upload(plupload, dir);
            //判断文件是否上传成功（被分成块的文件是否全部上传完成）
            if (PluploadUtil.isUploadFinish(plupload)) {
                //File uploadFile = new File(dir.getPath(), plupload.getFileName());
                //String imageName = plupload.getFileName().substring(plupload.getFileName().lastIndexOf(".") + 1) + ".jpg";
                //Video2ImageUtil.randomGrabberFFmpegImage(uploadFile.getPath(), dir.getPath(), imageName);
                Map<String, Object> data = new HashMap<>();
                data.put("fileName", plupload.getName());
                data.put("filePath", "files/" + videoPath + "/" + plupload.getFileName());
                data.put("smallPath", "files/" + videoPath + "/" + plupload.getSmallFileName());
                data.put("message", plupload.getChunk() + "," + plupload.getName() + "," + plupload.getChunks());
                return new FebsResponse().success().data(data);
            } else {
                return new FebsResponse().success().message(plupload.getChunk() + "," + plupload.getName() + "," + plupload.getChunks());
            }
        } catch (Exception e) {
            return new FebsResponse().fail().message("文件上传失败！Error：" + e.getMessage());
        }
    }

    private static String dateFormat() {
        String formatDay = DateFormatUtils.format(System.currentTimeMillis(), "yyyyMMdd");
        return formatDay;
    }

    /**
     * 文件类型判断
     *
     * @param fileName
     * @return
     */
    private static boolean checkFileType(String fileName, String[] allowFiles) {
        Iterator<String> type = Arrays.asList(allowFiles).iterator();
        while (type.hasNext()) {
            String ext = type.next();
            if (fileName.toLowerCase().endsWith(ext)) {
                return true;
            }
        }
        return false;
    }

}
